//
//  JATextView.swift
//  JAWeiBo
//
//  Created by Arvin on 17/4/11.
//  Copyright © 2017年 Arvin. All rights reserved.
//

import UIKit

class JATextView: UITextView {

   ///占位的文字
    var placeHoder: String = "请输入文字..." {
        didSet {
            
            plable.text = placeHoder
        }
    }
    
    /// 重写font的属性
    override var font: UIFont? {
        didSet {
            plable.font = font
        }
    }
    
    ///占位符的label
    fileprivate lazy var plable: UILabel = {
        
    let label = UILabel(title: nil, textColor: UIColor.lightGray, fontSize: 14)
    
    label.font = self.font
        
        return label
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
        
        //在初始化textView时, 设置一个font的默认值, 会调font属性的didSet方法, 将占位lable的font设置与自己的font一至
        self.font = UIFont.systemFont(ofSize: 14)
        
        //接收通知, 监控textView的文本的长度, 决定是否显示placeHolder
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
        //在垂直方向添加回弹的效果
        self.alwaysBounceVertical = true
        //下拉时隐藏键盘
        self.keyboardDismissMode = .onDrag
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension JATextView {
    func textDidChange () {
        //判断文字的长度, 决定是否显示label
        plable.isHidden = self.text.characters.count > 0
    }
}

extension JATextView {
    func setupUI () {
        addSubview(plable)
        
        //scrollView的自动布局的问题, 默认情况下, right和bottom代表的是contentSize的width和height; 在一开始的时, 需要创建一个和scrollView一样的大小的view, 将scrollView撑开
        let view = UIView()
        insertSubview(view, at: 0)
        
        view.snp.makeConstraints { (make) in
            //edges相当于同时设top,right, bottom, left
            make.edges.width.height.equalTo(self)
        }
        
         //占位label, 调整点位label的布局,让其与textView的文字对齐
        plable.snp.makeConstraints { (make) in
             make.top.equalTo(self).offset(8)
            make.left.equalTo(self).offset(5)
             make.right.equalTo(self).offset(-5)
        }
    }
}

extension JATextView {
    func insertEmotion(emotion: JAEmotionModel) {
        //如果是emoji表情
        if emotion.type == 1 {
            let emotion = NSString.emoji(withStringCode: emotion.code)
            self.insertText(emotion!)
            //如果是图片表情
        } else {
            //创建一个不可变的表情的富文本
            let attachMent = NSTextAttachment()
            
            //给附件设置图片
            attachMent.image = UIImage(named: emotion.fullPngPath!)
            
            //给附件设置大小和位置
            attachMent.bounds = CGRect(x: 0, y: -3, width: self.font!.lineHeight, height: self.font!.lineHeight)
            let attachmentString = NSAttributedString(attachment: attachMent)
            
            //创建一个可变的表情富文本
            let mattachmentString = NSMutableAttributedString(attributedString: attachmentString)
            
            //给表情富文本添加属性
            mattachmentString.addAttributes([NSFontAttributeName: self.font!], range: NSMakeRange(0, mattachmentString.length))
            
            //获取当前的textView的富文本的副本
            let atrributedString = self.attributedText.copy() as! NSAttributedString
            
            //用textView的富文本生成一个可变的富文本
            let matrributedString = NSMutableAttributedString(attributedString: atrributedString)
            
            //取到光标的位置
            var range = self.selectedRange
            
            //向textView的富文本书中插入一个表情文本
            matrributedString.replaceCharacters(in: range, with: mattachmentString)
            
            //插入完成后,将光标往后移动一个长度
            range.location += 1
            range.length = 0
            
            //设置attributedText 为新的富文本
            //给textView的富文本设置文本属性
            matrributedString.addAttributes([NSFontAttributeName: self.font!], range: NSMakeRange(0, matrributedString.length))
            
            //设置attributedText的属性值
            self.attributedText = matrributedString
            
            //重新定位光标
            self.selectedRange = range
            
        }
        
        //手动发送通知
        let notification = Notification(name: Notification.Name.UITextViewTextDidChange)
        NotificationCenter.default.post(notification)
        
        //手动调用代理
        self.delegate?.textViewDidChange!(self)
    }
}
